package com.tangguangdi.shield.server.filter;

import com.tangguangdi.base.common.variable.RegisterVar;
import com.tangguangdi.shield.server.permission.PermissionResult;
import com.tangguangdi.shield.server.permission.PermissionServer;
import com.tangguangdi.shield.server.properties.ShieldProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private PermissionServer permissionServer;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        PermissionResult result = permission(exchange);
        if (result.isSuccess()) {
            String userId = "0";
            if (result.getUser() != null) {
                userId = result.getUser().getId().toString();
            }
            ServerHttpRequest host = exchange.getRequest().mutate()
                    .header(RegisterVar.userKey, userId)
                    .build();
            return chain.filter(exchange.mutate().request(host).build());
        }
        exchange.getResponse().setStatusCode(result.getCode());
        return exchange.getResponse().setComplete();
    }

    private PermissionResult permission(ServerWebExchange exchange) {
        String url = exchange.getRequest().getPath().pathWithinApplication().value();
        String method = exchange.getRequest().getMethodValue();
        String token = exchange.getRequest().getHeaders().getFirst(RegisterVar.tokenKey);
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return permissionServer.check(route.getId(), url, method, token);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
